﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using GMS.Model;
using System.Collections.Generic;//for list
using GMS.Utils;
using System.Text.RegularExpressions;
//using GMS.Utils.ServiceContext;
using GMS.BLL;
using GMS.Web.CommonPage;
using Maticsoft.DBUtility;

public partial class System_SysParameters_Default : GMS.Web.CommonPage.BasePage.CommonBase
{
    HtmlProvider MC = new HtmlProvider();
    public ComOperate CDO = new ComOperate();
    ManageControls MCls = new ManageControls();
    //DBAndBizTableConverter BizTab = new DBAndBizTableConverter();

    public string tabBizType = string.Empty;
    public DataSet tableDs = new DataSet();//数据集
    private const string tablecode = "TAB_SYSPARAMETERS";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
            tableCode = tablecode;
            tabDBCode = tableCode;
            tabBizType = "";
            CDO = new ComOperate(tabDBCode);
            Dictionary<string, string> initConditions = new Dictionary<string, string>();
            if (Request.QueryString["typeid"] == null)
                initWhere = "a.FATHERTYPEID=0";
            else
                initWhere = "a.FATHERTYPEID='" + Request.QueryString["typeid"].ToString() + "'";

            tableDs = CDO.GetComData(tabDBCode, initWhere, 0, int.Parse(txtRowinOnePage.Text), null, null);

            if (tableDs == null || tableDs.Tables.Count == 0)
                return;
            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());

            //加载查询条件
            CDO.SetSearchRelation(null);
            DataSet dsSearch = CDO.GetRelationDataSet();
            LoadSearchControl(dsSearch);

            InitPageProperty();

            //加载数据列表
            if (tableDs == null || tableDs.Tables.Count == 0)
                return;
            LoadData(tableDs, 0, int.Parse(txtRowinOnePage.Text));

            SetViewStateData();
        }
        else
        {
            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "将控件补上字符", "<script>FillControl();</script>");
        }
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        if (ViewState["TabName"] == null)
        {            
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
                ViewState["TabName"] = GMS.BLL.TabInfoAccessBLL.GetTabName(tablecode);
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
                ViewState["TabName"] = GMS.BLL.TabInfoBLL.GetTabName(tablecode);
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
                ViewState["TabName"] = GMS.BLL.TabInfoOraBLL.GetTabName(tablecode);
            else
                return;
        }
        lblTabName.Text = ViewState["TabName"].ToString();
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        isRestored = false;
    }


    //特别注意：front：表示从查出来的ds.Tables[0]里面的第front行开始，end行结束，而不是数据库里面的第几行开始和结束
    public void LoadData(DataSet ds, int front, int end)
    {
        try
        {
            lblTabName.Text = ViewState["TabName"].ToString();
            if (ds == null || ds.Tables.Count == 0) //条件查询等要调用的LoadData（），必须判读
                return;

            lblAllRow.Text = totalRecordNum.ToString();

            DataTable dt = ds.Tables[0];
            tab_content.InnerHtml = "";
            
            CDO.Init(tableCode);
            CDO.SetListShowColAdnKeyDic();
            Dictionary<string, TabColumns> tabColumns = CDO.TabListShowedColDict;
            Dictionary<string, string> keys = CDO.TabKeyDict;

            string tKeys = "";
            string tabDBCode = string.Empty;

            Dictionary<string, string>.Enumerator de = keys.GetEnumerator();
            //获取主键
            for (; de.MoveNext(); )
            {
                tKeys += de.Current.Key + ",";
            }
            string[] arr = tKeys.Substring(0, tKeys.Length - 1).Split(',');
            //要显示的列
            //int showColNum = 0;

            string columnsString = "";

            //Dictionary<string, CheckInfoWithCon> checkCon = new Dictionary<string, CheckInfoWithCon>();
            StringBuilder tbodyStr = new StringBuilder();
            if (dt.Rows.Count > 0)
            {
                DelButton.Visible = true;
            }
            string[] colHtmls = TableUtility.ToColumnHtml(tabColumns, dt);
            if (colHtmls.Length > 0)
            {
                tbodyStr.Append("<tr style='font-weight:bold;' class='trTitle'>");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("<td width='26px' rowspan='" + colHtmls.Length + "' class='tdSelAll' style='text-align:center' >");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("<input name=\"chk_all\" type=\"checkbox\" onclick=\"CheckParaAll(this,'chk_item');\" />");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("</td>");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("<td width='30px' rowspan='" + colHtmls.Length + "' class='tdDataInfo' >");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("<nobr>序号</nobr>");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("</td>");
                tbodyStr.Append("\r\n");
                tbodyStr.Append("<td width='400px'>");
                tbodyStr.Append("<a href='#' title='全部收起' onclick='ExpandAll(this)' id='explanAllAchor'>");
                tbodyStr.Append("全部收起");
                tbodyStr.Append("</a>");
                tbodyStr.Append("</td>");

                for (int i = 0; i < colHtmls.Length; i++)
                {
                    tbodyStr.Append(colHtmls[i]);
                    tbodyStr.Append("\r\n");
                }
                tbodyStr.Append("</tr>");
                tbodyStr.Append("\r\n");
            }
            if (dt.Rows.Count == 0)
            {
                tbodyStr.Append("<tr>");
                tbodyStr.Append("<td colspan='4'>查找不到任何记录！</td>");
                tbodyStr.Append("</tr>");
                tbodyStr.Append("\r\n");
                tab_content.InnerHtml += tbodyStr.ToString();
                return;
            }

            columnsString = ",";
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (tabColumns.ContainsKey(dt.Columns[i].Caption.ToUpper()))
                {
                    if (tabColumns[dt.Columns[i].Caption].COLSHOWED == 1)
                    {
                        columnsString += dt.Columns[i].Caption.ToUpper() + ",";
                    }
                }
            }

            string[] arrColumns = columnsString.Split(',');
            //设置每列显示字符串最大长度
            int colMaxSize;
            colMaxSize = int.TryParse(SysSettings.GetTDMaxLength(),out colMaxSize) ? colMaxSize : 20;
            string fatherid = "0";
            ShowDataRow(arr, front, end, arrColumns, colMaxSize, dt, ref tbodyStr, fatherid, true, "");

            tab_content.InnerHtml += tbodyStr.ToString();
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('表格数据读取出错:" + comUse.SafeAlertMsg(ex.Message) + "');</script>");
        }
    }

    private void ShowDataRow(string[] arr, int front, int end, string[] arrColumns, int colMaxSize, DataTable dt, ref StringBuilder tbodyStr, string fatherid, bool display, string padSpace)
    {
        for (int i = front; (i < dt.Rows.Count) && (i < end); i++)
        {
            string dataId = "";
            string id = "";
            string proteyValue = dt.Rows[i]["PROPERTYVALUE"].ToString();;
            bool showExpand = false;
            for (int z = 0; z < arr.Length; z++)
            {
                dataId += arr[z] + "-" + dt.Rows[i][arr[z]].ToString() + ";";
                id = dt.Rows[i][arr[z]].ToString();
            }
            DataSet childTableDs = CDO.GetDSByComCondition(tablecode, null, "fathertypeid=" + id + "", 0, int.MaxValue, null, null, null); 


            if (childTableDs != null && childTableDs.Tables[0].Rows.Count > 0)
            {
                showExpand = true;
            }

            dataId = dataId.TrimEnd(';');
            if (display)
                tbodyStr.Append("<tr id='child_" + fatherid + "_" + id + "' style='display:block' onmouseover='change_tr_backgroundColor_move(this);' onmouseout='change_tr_backgroundColor_out(this);'>");
            else
            {
                tbodyStr.Append("<tr id='child_" + fatherid + "_" + id + "' style='display:block' onmouseover='change_tr_backgroundColor_move(this);' onmouseout='change_tr_backgroundColor_out(this);'>");
            }
            tbodyStr.Append("\r\n");
            tbodyStr.Append("<td style=\" text-align:center\">");
            tbodyStr.Append("\r\n");
            tbodyStr.Append("<input name=\"chk_item\" type=\"checkbox\" value='" + dataId + "' onclick=\"CheckParameterItem(this,'chk_all','child_" + fatherid + "_" + id + "');\" />");
            tbodyStr.Append("\r\n");
            tbodyStr.Append("</td>");
            tbodyStr.Append("\r\n");
            int num = (int.Parse(lblCpi.Text.ToString()) - 1) * int.Parse(txtRowinOnePage.Text.ToString()) + i + 1;
            tbodyStr.Append("<td>" + num + "</td>"); //显示序号
            tbodyStr.Append("\r\n");
            tbodyStr.Append("<td>");
            tbodyStr.Append("\r\n");

            if (showExpand)
            {
                tbodyStr.Append(padSpace);

                tbodyStr.Append("<a href='#' onclick=\"ExpandChildren(this,'child_" + fatherid + "_" + id + "')\" title='收起子参数' style='text-decoration:none'>");
                tbodyStr.Append("收起");
                tbodyStr.Append("</a>");
            }
            else
            {
                tbodyStr.Append(padSpace);
                tbodyStr.Append("<span style='color:gray'>收起</span>");
            }
            tbodyStr.Append("\r\n");

            tbodyStr.Append("&nbsp;&nbsp;&nbsp;&nbsp;");
            tbodyStr.Append("<a href='#' title='在当前节点下添加子类型,添加根节点请点击上面的“新建类型”' onclick=\"EditModel(this,\'" + id + "\',\'" + id + "\');\">");
            tbodyStr.Append("添加子类型");
            tbodyStr.Append("</a>");

            tbodyStr.Append("\r\n");
            tbodyStr.Append("</td>");
            tbodyStr.Append("\r\n");
            for (int j = 0; j < arrColumns.Length; j++)
            {
                if (arrColumns[j].Length > 0)
                {
                    //showColNum++;
                    string colValue = dt.Rows[i][arrColumns[j]].ToString();

                    tbodyStr.Append("<td style=\" text-align:left\" title='" + colValue + "'>");
                    tbodyStr.Append("\r\n");
                    tbodyStr.Append(padSpace);
                    tbodyStr.Append("<span style=\" text-align:left; cursor:pointer; \" onmousemove=\"change_Style_Mouse_Move(this);\" onmouseout=\"change_Style_Mouse_Out(this);\" onclick=\"EditModel(this,'" + id + "','" + (fatherid.Contains("_") ? fatherid.Substring(fatherid.LastIndexOf('_') + 1) : fatherid) + "','" + proteyValue + "');\">");
                    tbodyStr.Append(Trucate(colValue, colMaxSize));
                    tbodyStr.Append("</span>");
                    tbodyStr.Append("\r\n");
                    tbodyStr.Append("</td>");
                    tbodyStr.Append("\r\n");
                }
            }
            tbodyStr.Append("</tr>");

            //添加子类型行

            if (showExpand)
            {
                DataTable childDT = childTableDs.Tables[0];
                string padSpace2 = padSpace + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                ShowDataRow(arr, 0, childDT.Rows.Count, arrColumns, colMaxSize, childDT, ref tbodyStr, fatherid + "_" + id, false, padSpace2);
            }
            tbodyStr.Append("\r\n");
        }
    }

    /// <summary>
    /// 加载查询控件
    /// </summary>
    /// <param name="dsData"></param>
    public void LoadSearchControl(DataSet dsData)
    {
        tbQueryCls.InnerHtml = "";
        int iType = 0, iColNum = 0, iDisNum = 4;
        string SelId = string.Empty;
        string SelName = string.Empty;
        string strValue = string.Empty;
        DataTable dtTables = new DataTable();
        Dictionary<string, GMS.Model.TabColumns> relation = new Dictionary<string, GMS.Model.TabColumns>();

        CDO.SetTabColDicAndKeyDic(tableCode);
        Dictionary<string, GMS.Model.TabColumns> tabColumns = CDO.TabColDict;

        StringBuilder qryHTML = new StringBuilder();

        qryHTML.Append("<tr>");
        txtQueryCls.Text = "";
        DataSet relateDS;

        foreach (GMS.Model.TabColumns tabCol in tabColumns.Values)
        {
            if (tabCol.COLSEARCH == (int)GMS.Utils.EnumHelper.E_YesOrNo.No)
                continue;

            if (iColNum % iDisNum == 0)
                qryHTML.Append("</tr>\r\n<tr>");//换行
            iColNum++;
            iType = tabCol.COLTYPE;

            relateDS = new DataSet();
            string value = "";
            if (!string.IsNullOrEmpty(tabCol.FOREIGNTAB))
            {
                //表示关联的，那么肯定是下拉框的
                iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_DDL;

                DataTable tempDT;
                if (dsData.Tables.Contains(tabCol.COLCODE.ToUpper()))
                {
                    tempDT = dsData.Tables[tabCol.COLCODE.ToUpper()].Copy();
                    relateDS.Tables.Add(tempDT);
                }
                //if (tabCol.FOREIGNTAB.Equals("TAB_CITY") && OP.CitySelected != "")
                //    value = OP.CitySelected.Trim('\'');


                foreach (DataTable dt in dsData.Tables)
                {
                    //当行列是当前表某列的父列
                    if (dt.TableName.ToUpper().StartsWith(tabCol.COLCODE.ToUpper() + "-"))
                    {
                        dtTables = dt;
                        tempDT = dt.Copy();
                        relateDS.Tables.Add(tempDT);
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        continue;
                    }
                    if (dt.TableName.ToUpper().Contains("-" + tabCol.COLCODE.ToUpper() + "-"))  //父级获得所有父级子级数据
                    {
                        dtTables = null;
                        iType = (int)GMS.Utils.EnumHelper.E_ColDataType.COL_FDDL;
                        break;
                    }
                }

                SelId = tabCol.FOREIGNCOL;
                SelName = tabCol.FOREIGNSHOWCOL;
            }
            try
            {
                //display sysArr
                qryHTML.Append(MC.GetSysObjScripts(relateDS, tabCol.FOREIGNTAB));
                //DisplayQuerys
                qryHTML.Append(MC.DisplayQuerys(iType, false, tabCol.COLCODE.ToUpper(), tabCol.COLNAME, value, relateDS, "", SelId, SelName));
            }
            catch (Exception ex)
            {
                this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询控件加载出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
            }
            if (iType == (int)EnumHelper.E_ColDataType.COL_DATE)
            {
                iColNum++;
                txtQueryCls.Text += "S_Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
                txtQueryCls.Text += "E_Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
            }
            else
                txtQueryCls.Text += "Cls-" + tabCol.COLCODE + "-" + iType.ToString() + ";";
        }
        if (iColNum == 0)
        {
            this.btnQueryNormal.Visible = false;
            this.btnQueryCustom.Visible = false;
        }
        qryHTML.Append("</tr>");
        tbQueryCls.InnerHtml = qryHTML.ToString();
    }

    protected void btnQuery_ServerClick(object sender, EventArgs e)
    {
        string sQuery = string.Empty;
        try
        {
            Dictionary<string, string> values = new Dictionary<string, string>();
            int end = int.Parse(txtRowinOnePage.Text);
            lblCpi.Text = "1";
            GetViewStateData();
            values = GetSearchCondition("", txtQueryCls.Text);
            txtQueryData.Value = queryColData;

            string sqlWhere = string.Empty;
            if (values.Count > 0)
            {
                CDO.GetConditionStr(ref sqlWhere, values, tabDBCode);
            }
            if (initWhere.Length > 0)
            {
                if (sqlWhere.Length > 0)
                    sqlWhere = sqlWhere + " and " + initWhere;
                else
                    sqlWhere = initWhere;
            }

            DataSet tableDs = CDO.GetComData(tabDBCode, sqlWhere, 0, end, null, /*OP.CitySelectRight*/null);

            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            InitPageProperty();
            LoadData(tableDs, 0, end + 1); //从查出来的dt里面的第1行开始。   
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询数据读取出错:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    //查询
    protected void SearchData(int start, int end)
    {
        GetViewStateData();
        Dictionary<string, string> values = null;
        DataSet tableDs = null;
        string sqlwhere = string.Empty;
        if (comSearch)
        {
            values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
            if (values.Count > 0)
            {
                CDO.GetConditionStr(ref sqlwhere, values, tabDBCode);
            }
            txtQueryData.Value = queryColData;
        }
        else
        {
            sqlwhere = hidCustomWhere.Value;
        }
        if (initWhere.Length > 0)
        {
            if (sqlwhere.Length > 0)
                sqlwhere += " and " + initWhere;
            else
                sqlwhere = initWhere;
        }
        tableDs = CDO.GetComData(tabDBCode, sqlwhere, start, end, null, /*OP.CitySelectRight*/null);// CDO.

        totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
        ViewState["totalRecordNum"] = totalRecordNum;
        lblallPage.Text = (totalRecordNum / int.Parse(txtRowinOnePage.Text.ToString()) + 1).ToString();//页的总数量
        LoadData(tableDs, 0, end - start + 1); //从查出来的dt里面的第1行开始。
    }

    //调用查询
    protected void SearchButtonClick(object sender, EventArgs e)
    {
        try
        {
            int pageSize = int.Parse(txtRowinOnePage.Text);
            lblCpi.Text = "1";
            SearchData(0, pageSize); //点击查询的时候，都是从第一页开始显示的
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询数据出错:" + comUse.SafeAlertMsg(ex.Message) + "');</script>");//关闭窗口
        }
    }

    //删除数据
    protected void DelButtonClick(object sender, EventArgs e)
    {
        if (isRestored)
            return;
        string ids = Request.Form["chk_item"].Replace("SYSPARAMETERSID-", "");
        if (string.IsNullOrEmpty(userAccount))
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return;
        }
        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.DeleteMulti(ids, userAccount);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.DeleteMulti(ids, userAccount);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSORABLL bll = new SYSPARAMETERSORABLL();
                bll.DeleteMulti(ids, userAccount);
            }
            else
                return;
          
            Alert("删除成功！");
            ReBindData();
        }
        catch (ArgumentException ex)
        {
            Alert("删除失败！"+comUse.SafeAlertMsg(ex.Message));
        }
         catch(Exception ex)
        {
            Alert("删除失败！" + comUse.SafeAlertMsg(ex.Message));
        }
    }

    //点击列进行排序
    protected void SortButtonClick(object sender, EventArgs e)
    {
        try
        {
            GetViewStateData();
            string str = SortTxt.Value;
            int curPage = int.Parse(lblCpi.Text.ToString());
            int pageSize = int.Parse(txtRowinOnePage.Text);
            int start = (curPage - 1) * pageSize;
            int end = curPage * pageSize;
            Dictionary<string, string> values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
            txtQueryData.Value = queryColData;

            CDO.SetTabColDicAndKeyDic(tableCode);
            Dictionary<string, GMS.Model.TabColumns> tabColDict = CDO.TabColDict;
            if (tabColDict == null || tabColDict.Count == 0)
                return;
            string sortStr = null;
            foreach (KeyValuePair<string, GMS.Model.TabColumns> kvp in tabColDict)
            {
                if (str.Equals(kvp.Value.COLNAME))
                {

                    if (sortAsc == true)
                    {
                        sortAsc = false;
                        sortStr = " order by a." + kvp.Value.COLCODE + " DESC";
                    }
                    else
                    {
                        sortAsc = true;
                        sortStr = " order by a." + kvp.Value.COLCODE + " ASC";
                    }

                    ViewState["sortAsc"] = sortAsc; //更新sortAsc(值已经改变）
                    break;
                }

            }
            DataSet tableDs;

            string sqlwhere = string.Empty;
            if (comSearch && values.Count > 0)
            {

                CDO.GetConditionStr(ref sqlwhere, values);
            }
            else
            {
                sqlwhere = hidCustomWhere.Value;
            }
            if (initWhere.Length > 0)
            {
                if (sqlwhere.Length > 0)
                    sqlwhere += " and " + initWhere;
                else
                    sqlwhere = initWhere;
            }
            tableDs = CDO.GetComData(tabDBCode, sqlwhere, start, end, sortStr, /*OP.CitySelectRight*/null);
            LoadData(tableDs, 0, tableDs.Tables[0].Rows.Count);
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('排序出现异常错误:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    #region export part
    protected void Btn_Export(object sender, EventArgs e)
    {
        //int i = 0;
        DataSet ds;

        //根据当前的条件进行查询
        Dictionary<string, string> values;
        values = GetSearchCondition("", txtQueryCls.Text);
        ds = CDO.DsComExportData(tableCode, values, null, /*OP.CitySelectRight*/null, null);

        if (ds == null)
        {
            Alert("没有可导出数据！");
            return;
        }
        //设置导出文件名
        ExportToFile(ds, 1);
    }

    public void ExportToFile(DataSet ds, int typeId)
    {
        string fileName = lblTabName.Text + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
        fileName = Server.UrlEncode(fileName);
        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);

        // typeid==1时导出为EXCEL格式文件；typeid==2时导出为XML格式文件 
        if (typeId == 1)
        {
            //显示中文名的列标题：
            DataTable dt = ds.Tables[0];
            CDO.SetExportCol(tableCode);
            GMS.Web.CommonPage.TableUtility.ToExcelBook(CDO.TabExportColDict, dt).Save(resp.OutputStream);
        }
        else if (typeId == 2)
        {
            //从DataSet中直接导出XML数据并且写到HTTP输出流中 
            resp.Write(ds.GetXml());
        }
        //写缓冲区中的数据到HTTP头文件中 
        resp.End();
    }
    #endregion

    #region page part
    private void InitPageProperty()
    {
        this.JumpPage.Text = this.lblCpi.Text;
        if (totalRecordNum <= int.Parse(txtRowinOnePage.Text.ToString()))
        {
            LbtNextPage.Enabled = false;
            LbtLastPage.Enabled = false;
        }
        else
        {
            LbtNextPage.Enabled = true;
            LbtLastPage.Enabled = true;
        }
        lblallPage.Text = (totalRecordNum / int.Parse(txtRowinOnePage.Text.ToString()) + 1).ToString();//页的总数量
        LbtFirstPage.Enabled = false;
        LbtPreviousPage.Enabled = false;
    }

    /// <summary>
    /// 首页按钮
    /// </summary>
    protected void FirstPageClick(object sender, EventArgs e)
    {
        lblCpi.Text = "1";
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

    }
    /// <summary>
    /// 上一页
    /// </summary>
    protected void PreviousPageClick(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) > 1)
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) - 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 下一页
    /// </summary>
    protected void NextPageClick(object sender, EventArgs e)
    {
        if (int.Parse(lblCpi.Text) < int.Parse(lblallPage.Text))
        {
            lblCpi.Text = (int.Parse(lblCpi.Text) + 1).ToString();
            DBbind(lblCpi.Text);
            this.JumpPage.Text = this.lblCpi.Text;
        }
    }
    /// <summary>
    /// 尾页
    /// </summary>
    protected void LastPageClick(object sender, EventArgs e)
    {
        lblCpi.Text = lblallPage.Text.Equals("0") ? "1" : lblallPage.Text;
        DBbind(lblCpi.Text);
        this.JumpPage.Text = this.lblCpi.Text;

        this.LbtFirstPage.Enabled = true;
        this.LbtLastPage.Enabled = false;
    }
    /// <summary>
    /// 绑定数据
    /// </summary>
    public void DBbind(string curNum)
    {
        GetViewStateData();
        if (curNum.Equals("0"))
            curNum = "1";

        LbtFirstPage.Enabled = true;
        LbtLastPage.Enabled = true;
        LbtPreviousPage.Enabled = true;
        LbtNextPage.Enabled = true;

        int curPage = int.Parse(curNum);
        int pageSize = int.Parse(txtRowinOnePage.Text);
        int start = (curPage - 1) * pageSize;
        int end = curPage * pageSize;
        SearchData(start, end);


        //算出总的页数
        if (totalRecordNum % pageSize != 0)
        {
            lblallPage.Text = (totalRecordNum / pageSize + 1).ToString();//页的总数量
        }
        else
        {
            lblallPage.Text = (totalRecordNum / pageSize).ToString();
        }        //绑定到数据源

        if (this.lblallPage.Text.ToString().Equals("0"))//0页
        {
            this.lblCpi.Text = "0";
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else if (this.lblallPage.Text.ToString().Equals("1"))//1页
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
            this.JumpPage.Enabled = false;
        }
        else //多页
        {
            this.LbtNextPage.Enabled = true;
            this.LbtLastPage.Enabled = true;
            this.JumpPage.Enabled = true;

        }
        //判断是首页 
        if (curNum.Equals("1"))
        {
            this.LbtFirstPage.Enabled = false;
            this.LbtPreviousPage.Enabled = false;
        }
        //判断是尾页
        if (lblallPage.Text.ToString().Equals(curNum))
        {
            this.LbtNextPage.Enabled = false;
            this.LbtLastPage.Enabled = false;
        }

        if (!lblAllRow.Text.Equals("0") && curNum.Equals("1"))
        {
            this.lblCpi.Text = "1";
        }
    }
    protected void txtRowinOnePage_TextChanged(object sender, EventArgs e)
    {
        check_txtRowinOnePage();
        DBbind(this.lblCpi.Text);
    }
    public void check_txtRowinOnePage()//检查输入每页的行数
    {
        if (txtRowinOnePage.Text.Trim().Equals("") || !comUse.IsNumber(txtRowinOnePage.Text.Trim()))
        {
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
            return;
        }
        if (int.Parse(txtRowinOnePage.Text) < 1)
            txtRowinOnePage.Text = SysSettings.GetSysSetting("每页记录数");
    }
    protected void JumpPageTextChanged(object sender, EventArgs e)//第几页
    {
        if (this.JumpPage.Text == null || !comUse.IsNumber(this.JumpPage.Text))
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('请输入整数！');</script>");
            return;
        }

        if (int.Parse(this.JumpPage.Text) > 0 && int.Parse(this.JumpPage.Text) <= int.Parse(this.lblallPage.Text))
        {
            this.lblCpi.Text = this.JumpPage.Text;
            DBbind(this.JumpPage.Text);
        }
        else
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('超过页数范围，请重新输入！');</script>");
        }
    }

    #endregion

    protected void BtnRemark_Click(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        string url = "../../Public/TabRemark.aspx?table=" + tableCode;
        this.Page.Response.Redirect(url);
    }

    protected void BtnImportClick(object sender, EventArgs e)
    {
        tableCode = (string)ViewState["tableCode"];
        //string url = "../../DMWEB/ExcelImport/Default.aspx?TableName=" + tableCode;
        string url = "~/public/ExcelImport/ExcelDbImport.aspx?TableName=" + tableCode; 
        this.Page.Response.Redirect(url);
    }


    //按照输入的最大长度截短字符串
    private string Trucate(string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value))
            return "&nbsp;";
        if (maxLength > 0 && value.Length > maxLength)
            value = value.Substring(0, maxLength - 1) + "...";
        return value;
    }
    protected void BtnCustomAdd_Click(object sender, EventArgs e)
    {
        //lbCustomColCode.Text:字段名（英文）
        //lbCustomOpr.Text：操作符（如>, <, = like等
        //tbCustomSel.Text：保存显示的条件
        //hidCustomWhere.Value：保存真实的查询条件

        string whereValue = TBInptValue.Text.Trim();
        string colcode = lbCustomColCode.Text.ToUpper();
        int numForeign = 0;//关联表第几个关联

        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];
        if (lbCustomColCode.Text.Length == 0 || lbCustomOpr.Text.Length == 0)
        {
            Alert("请选择列和条件！");
            return;
        }

        if (whereValue.Length == 0)
        {
            Alert("值不能为空！");
            return;
        }
        whereValue = StringHelper.SafeSQLString(whereValue);


        CDO.SetTabColDicAndKeyDic(tableCode);
        string foreignTab = CDO.TabColDict[colcode].FOREIGNTAB.ToUpper();
        int type = CDO.TabColDict[colcode].COLTYPE;
        string chineseColName = CDO.TabColDict[colcode].COLNAME;
        //模糊匹配
        if (lbCustomOpr.Text == "like")
        {
            if (type == (int)EnumHelper.E_ColDataType.COL_STRING || foreignTab.Length > 0)
                whereValue = "%" + whereValue + "%";
            else
            {
                Alert(chineseColName + "类型限制，不能进行模糊匹配,请更改条件或列！");
                return;
            }
        }
        //操作符
        if (tbCustomSel.Text.Length > 0 && hidCustomWhere.Value.Length > 0)
        {
            if (Request.Form["radioWhere"] == "and")
            {
                tbCustomSel.Text += "<br/> 并且 ";
                hidCustomWhere.Value += "and ";
            }
            else
            {
                tbCustomSel.Text += "<br/> 或者 ";
                hidCustomWhere.Value += "or ";
            }
        }

        //显示条件
        tbCustomSel.Text += chineseColName + lbCustomOpr.SelectedItem.Text + whereValue;

        //查询条件
        if (foreignTab.Length == 0)
        {
            if (type == (int)EnumHelper.E_ColDataType.COL_BOOL || type == (int)EnumHelper.E_ColDataType.COL_AUTOID
                || type == (int)EnumHelper.E_ColDataType.COL_INT || type == (int)EnumHelper.E_ColDataType.COL_FLOAT)
            {
                hidCustomWhere.Value += "a." + colcode + " " + lbCustomOpr.Text + " " + whereValue + "  ";
            }
            else if (type == (int)EnumHelper.E_ColDataType.COL_TIME || type == (int)EnumHelper.E_ColDataType.COL_DATE)
            {                //时分秒？            
                hidCustomWhere.Value += "to_char(" + "a." + colcode + ",'yyyy-mm-dd')" + lbCustomOpr.Text + "'" + whereValue + "'  ";
            }
            else //字符串
            {
                hidCustomWhere.Value += "a." + colcode + " " + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
        }
        else
        {
            foreach (GMS.Model.TabColumns col in CDO.TabColDict.Values)
            {
                if (foreignTab.Equals(col.FOREIGNTAB.ToUpper()))
                    numForeign++;
                if (colcode == col.COLCODE.ToUpper())
                    break;
            }

            if (foreignTab.Equals(ConstantHelper.C_SYSPARA_TABNAME.ToUpper()))
            {
                hidCustomWhere.Value += "B" + numForeign + "." + CDO.TabColDict[colcode].FOREIGNSHOWCOL + " "
                    + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
            else //其他关联的表不设置别名，直接用表名
            {
                hidCustomWhere.Value += foreignTab + numForeign + "." + CDO.TabColDict[colcode].FOREIGNSHOWCOL + " "
                    + lbCustomOpr.Text + " \'" + whereValue + "\'  ";
            }
        }
    }


    protected void BtnCustomClear_Click(object sender, EventArgs e)
    {
        tbCustomSel.Text = string.Empty;
        hidCustomWhere.Value = string.Empty;
    }

    //自定义查询
    protected void BtnCustomSearch_Click(object sender, EventArgs e)
    {
        if (!isRestored)
        {
            comSearch = (bool)ViewState["comSearch"];
            if (comSearch)
                comSearch = false;
            else
                comSearch = true;
            ViewState["comSearch"] = comSearch;
            txtQueryData.Value = "";
            if (comSearch)//关闭自定义查询
            {
                tbCustom.Visible = false;
                tbQueryCls.Visible = true;
                btnQueryNormal.Visible = true;
                btnQueryCustom.Visible = false;
                BtnCustomSearch.Text = "复杂查询";
                BtnClear_S.Visible = true;
                BtnClear_CS.Visible = false;
                tab_content.EnableViewState = false;
                btnQuery_ServerClick(null, null);
                BtnClear_Click(null, null);
            }
            else//开启自定义查询
            {
                LisColData();
                tbCustom.Visible = true;
                tbQueryCls.Visible = false;
                btnQueryNormal.Visible = false;
                btnQueryCustom.Visible = true;
                BtnCustomSearch.Text = "简单查询";
                tab_content.EnableViewState = true;
                BtnClear_CS.Visible = true;
                BtnClear_S.Visible = false;
                lblallPage.Text = "0";
                lblAllRow.Text = "0";
                lblCpi.Text = "0";
                LbtFirstPage.Enabled = false;
                LbtLastPage.Enabled = false;
                LbtNextPage.Enabled = false;
                LbtPreviousPage.Enabled = false;
            }
        }
    }

    /// <summary>
    /// 加载自定义查询信息
    /// </summary>
    private void LisColData()
    {
        if (tableCode == null || tableCode.Equals(""))
            tableCode = (string)ViewState["tableCode"];
        DataTable dt = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsAccessBLL bll = new GMS.BLL.TabColumnsAccessBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsBLL bll = new GMS.BLL.TabColumnsBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            GMS.BLL.TabColumnsOraBLL bll = new GMS.BLL.TabColumnsOraBLL();
            dt = bll.GetColListAllowedOrderSEQ(tableCode);
        }
        else
            return;
       
        if (dt != null)
        {
            lbCustomColCode.DataTextField = "COLNAME";
            lbCustomColCode.DataValueField = "COLCODE";
            lbCustomColCode.DataSource = dt;
            lbCustomColCode.DataBind();

            Dictionary<string, string> cols = new Dictionary<string, string>();
            foreach (DataRow row in dt.Rows)
            {
                cols.Add(row["COLCODE"].ToString(), row["COLNAME"].ToString());
            }
        }
    }
    protected void BtnClear_Click(object sender, EventArgs e)
    {
        TBInptValue.Text = string.Empty;
        tbCustomSel.Text = string.Empty;
        hidCustomWhere.Value = string.Empty;
    }
    protected void BtnCustomSearchOpr_Click(object sender, EventArgs e)
    {
        GetViewStateData();
        int pageSize = int.Parse(txtRowinOnePage.Text);
        try
        {
            //点击查询的时候，都是从第一页开始显示的      
            CDO.IsCustomSearch = true;
            string sqlwhere = hidCustomWhere.Value;


            if (initWhere.Length > 0)
            {
                if (sqlwhere.Length > 0)
                    sqlwhere += " and " + initWhere;
                else
                    sqlwhere = initWhere;
            }

            DataSet tableDs = CDO.GetComData(tabDBCode, sqlwhere, 0, pageSize, null, /*OP.CitySelectRight*/null);
            totalRecordNum = int.Parse(tableDs.Tables[1].Rows[0][0].ToString());
            ViewState["totalRecordNum"] = totalRecordNum;
            InitPageProperty();
            LoadData(tableDs, 0, pageSize - 0 + 1); //从查出来的dt里面的第1行开始。
        }
        catch (Exception ex)
        {
            this.Page.RegisterClientScriptBlock("toAlert", "<script>alert('查询出错，请检查查询条件:" + comUse.SafeAlertMsg(ex.Message + ex.StackTrace) + "');</script>");//关闭窗口
        }
    }

    //用于执行删除、新增或修改后重新加载数据
    private void ReBindData()
    {
        GetViewStateData();
        int pageSize = int.Parse(txtRowinOnePage.Text);
        SearchData(int.Parse(lblCpi.Text)-1, pageSize);
        //DataSet ds;
        //Dictionary<string, string> values = new Dictionary<string, string>();
        //values = GetSearchCondition(Txt_mysql.Value, txtQueryCls.Text);
        //ds = CDO.GetDSByComCondition(tabDBCode, values, null, 0, pageSize, null, null, null);
        //totalRecordNum = int.Parse(ds.Tables[1].Rows[0][0].ToString());
        //ViewState["totalRecordNum"] = totalRecordNum;
        //this.lblCpi.Text = "1";
        //InitPageProperty();
        //LoadData(ds, 0, pageSize);
    }

    protected void Button_Insert_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(userAccount))
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return;
        }

        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.Add(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"]);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.Add(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"]);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSORABLL bll = new SYSPARAMETERSORABLL();
                bll.Add(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"]);
            }
            else
                return;
           
            Alert("新建成功！");
            ReBindData();
        }
        catch (ArgumentException ex)
        {
            Alert("新建失败:" + comUse.SafeAlertMsg(ex.Message));
            return;
        }
        catch (Exception ex)
        {
            Alert("新建失败:" + comUse.SafeAlertMsg(ex.Message));
            return;
        }
       
        
    }
    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.Update(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"], Request.Form["iptPropertyId"]);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSACCESSBLL bll = new SYSPARAMETERSACCESSBLL();
                bll.Update(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"], Request.Form["iptPropertyId"]);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                GMS.BLL.SYSPARAMETERSORABLL bll = new SYSPARAMETERSORABLL();
                bll.Update(userAccount, Request.Form["iptPropertyName"], Request.Form["iptPropertyValue"], Request.Form["iptFatherid"], Request.Form["iptPropertyId"]);
            }
            else
                return;
          
            Alert("修改成功!");
            ReBindData();
        }
        catch (ArgumentException ex)
        {
            Alert("修改失败:" + comUse.SafeAlertMsg(ex.Message));
            return;
        }
        catch (Exception ex)
        {
            Alert("修改失败:" + comUse.SafeAlertMsg(ex.Message));
            return;
        }
    }
}
